<template>
  <div>
    <el-form ref="querForm" size="mini" inline="true" :model="querForm">
      <el-form-item label="服务名称">
        <el-input
          v-model="querForm.servicename"
          placeholder="请输入查询服务名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="角色">
        <el-button type="primary" @click="chaxun">查询</el-button>
        <el-button type="primary" @click="add">新增服务</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" v-loading="loading" style="width: 100%">
      <el-table-column prop="serviceid" label="serviceid" align="center" width="100">
      </el-table-column>
      <el-table-column prop="servicename" label="服务名称" align="center" width="100">
      </el-table-column>
      <el-table-column prop="servicecategory" label="服务类别" align="center" width="100">
      </el-table-column>
      <el-table-column prop="serviceprice" label="参考价格" align="center" width="100">
      </el-table-column>
      <el-table-column
        prop="description"
        label="服务保障"
        width="300"
      ></el-table-column>
      <el-table-column
        prop="serviceintroduction"
        label="服务介绍"
        width="300"
      ></el-table-column>

      <el-table-column align="center" prop="imageurl" label="服务图片" width="00">
        <template slot-scope="{ row }">
          <div>
            <span class="demonstration"> </span>
            <!-- 服务图片 -->
            <el-image
              class="el-image"
              :src="row.imageurl"
              fit="fill"
            ></el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <div class="buttonflex">
            <el-button
              class="el-button"
              @click="update(scope.row)"
              type="success"
              size="mini"
              >修改</el-button
            >
            <el-button
              class="el-button"
              @click="del(scope.row.serviceid)"
              type="danger "
              size="mini"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="el-pagination"
      background
      layout="prev, pager, next"
      @current-change="changePage"
      :page-size="querForm.pagesize"
      :total="total"
    >
    </el-pagination>

    <!-- 对话框 -->

    <el-dialog :title="title" :visible.sync="open">
      <!-- this.$refs.form.validate(valid) => {}  -->
      <el-form :rules="rules" ref="form" :model="form" label-width="150px" plac>
        <el-row>
          <el-col :span="12">
            <el-form-item label="servicename" prop="serveiname">
              <el-input v-model="form.servicename" placeholder="请填写服务名称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="servicecategory" prop="servicecategory">
              <el-select
                v-model="form.servicecategor"
                placeholder="请选择所属类别"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="serviceprice" prop="serviceprice">
              <el-input
                v-model="form.serviceprice"
                placeholder="服务价格不能超出1000"
                maxlength="4"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="description" prop="description">
              <el-input
                v-model="form.description"
                placeholder="服务保障内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item
              label="serviceintroduction"
              prop="serviceintroduction"
            >
              <el-input
                type="textarea"
                placeholder="请输入服务介绍"
                v-model="form.serviceintroduction"
                show-word-limit
                maxlength="70"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-upload
        class="avatar-uploader"
        action="https://jsonplaceholder.typicode.com/posts/"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-if="imageUrl" class="el-icon-plus avatar-uploader-icon">
          更换图片</i
        >
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
        <el-button type="primary" @click="submitFrom">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getservicelistlength,
  upload,
  list,
  cx,
  del,
  update,
  add,
} from "@/api/servicelist";
export default {
  name: "servicelist-index",
  data() {
    return {
      file: {},
      imageUrl: "",
      query: "",
      tableData: [],
      open: false,

      form: {},
      title: "",
      selectedrow: {},

      options: [
        {
          value: 1,
          label: "家电维修",
        },
        {
          value: 2,
          label: "水电维修",
        },
        {
          value: 3,
          label: "管道疏通",
        },
      ],

      querForm: {
        page: 1,
        pagesize: 6,
        servicename: "",
      },
      total: 50,
      loading: true,

      methods: "",

      rules: {
        servicename: [
          { required: true, message: "请输入服务名称", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3~10个字符", trigger: "blur" },
        ],
        servicecategory: [
          {
            required: true,
            message: "请填写服务类别 1 家电维修 2 水电维修 3 管道疏通",
            trigger: "blur",
          },
        ],
        serviceprice: [
          { required: false, message: "请填写服务价格", trigger: "blur" },
        ],

        description: [
          { required: true, message: "请填写服务保障", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.loadData();
  },
  methods: {
    loadData() {
      setTimeout(() => {
        this.loading = false;
      }, 500);
      list(this.querForm).then((resp) => {
        this.tableData = resp;
      });

      this.getservicelistlength();
    },

    //获取总数据条数
    getservicelistlength() {
      getservicelistlength().then((resp) => {
        this.total = resp;
      });
    },

    //查询
    chaxun() {
      this.querForm.page = 1;
      cx(this.querForm).then((resp) => {
        this.tableData = resp;
      });
    },

    changePage(page) {
      this.querForm.page = page;
      this.loadData();
    },

    add() {
      this.form = {};
      this.open = true;
      this.title = "添加服务";
      this.imageUrl = "";
      this.methods = "addService";
    },

    update(row) {
      this.open = true;

      // console.log(JSON.stringify(row)===JSON.stringify(row))

      this.selectedrow = row;
      this.form = JSON.parse(JSON.stringify(row));
      //传递图片
      this.imageUrl = row.imageurl;

      this.title = "修改用户";
      this.methods = "updateService";
    },

    submitFrom() {
      // console.log("数据改变");
      //判断验证是否通过
      this.$refs.form.validate((valid) => {
        if (valid) {
          //添加数据
          if (this.methods == "addService") {
            add(this.form).then((resp) => {
              if (resp == 1) {
                this.$message.success("添加成功");
                this.open = false;
                this.upload();
                this.loadData();
              }
              if (resp == 0) {
                this.$message.warning("服务名称已经存在");
              }
            });
          }

          //修改数据
          if (this.methods == "updateService") {
            //判断数据是否更改

            if (JSON.stringify(this.selectedrow) != JSON.stringify(this.form)) {
              // console.log(this.form);
              this.form.oldservicename = this.selectedrow.servicename;
              update(this.form).then((resp) => {
                if (resp == 1) {
                  this.$message.success("修改成功");

                  //更换图片
                  const formData = new FormData();
                  // 通过append向form对象添加数据
                  formData.append("img", this.file);
                  // 通过append向form对象添加数据
                  formData.append("servicename", this.form.servicename);
                  upload(formData);

                  this.open = false;
                  this.loadData();
                } else {
                  this.$message.warn("服务名称不可重复");
                }
              });
            } else {
              // console.log("数据未改变");
              this.$message.success("数据未发生改变");
              this.open = false;
            }
          }
        }
      });
    },

    del(serviceid) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        console.log(serviceid);
        del(serviceid).then(() => {
          this.$message.success("删除成功");
          this.loadData();
        });
      });
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.file = file.raw;
      console.log(this.file);

      this.form.imageurl = "图片被修改";
    },
    beforeAvatarUpload(file) {
      const isJPG = (file.type === "image/jpeg") | (file.type === "image/png");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    upload() {
      const formData = new FormData();
      // 通过append向form对象添加数据
      formData.append("img", this.file);
      // 通过append向form对象添加数据
      formData.append("servicename", this.form.servicename);

      upload(formData);
    },
  },
};
</script>

<style scoped>
.el-pagination {
  position: absolute;
  top: 850px;
}
.el-button {
  width: 70px;
}
.buttonflex {
  display: flex;
}

.avatar-uploader {
  padding: 50px;
  margin-left: 90px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-image {
  width: 75px;
  height: 75px;
}
</style>